from typing import List
from utils.JSON的输入和输出 import 读取json
from utils.字符utf8长度 import getStringLen
import zlib

m_iCryptoKey = 0xA2  # ! 记得改密钥


WORD_Text_json: list = 读取json(f"output/3_res/WORD_Text_zh.json")

merge_string = "\u0000" * 4  # 开始就有八个空

word_indx = [0]

for i in range(len(WORD_Text_json)):
    word = WORD_Text_json[i]

    length = getStringLen(word)
    if i == 0:
        length += 4
    space_len = 4 - length % 4  # 就是拿到余数
    word_indx.append(word_indx[-1] + length + space_len)  # 记录indx
    merge_string += word + "\u0000" * space_len

# 压缩
# 不能压缩 压缩反而出问题

word_indx = [0, 4] + word_indx[1:]


def intTo4Hex(num: int) -> List[int]:
    res = []
    for _ in range(4):
        res.append(num % 256)
        num //= 256
    return res


word_indx_merge = []
for item in word_indx:
    word_indx_merge.extend(intTo4Hex(item))

print(word_indx_merge)

# 直接加密
file_names = ["WORD_Text", "CARD_Desc", "CARD_Indx"]


def encrypt(output_name, b: bytes):

    data = bytearray(zlib.compress(b))

    for i in range(len(data)):
        v = i + m_iCryptoKey + 0x23D
        v *= m_iCryptoKey
        v ^= i % 7
        data[i] ^= v & 0xFF

    with open(output_name, "wb") as f:
        f.write((data))
    f.close()


encrypt(f"output/4_res/WORD_Text.txt", bytes(merge_string, encoding="utf-8"))
encrypt(f"output/4_res/WORD_Indx.txt", bytes(word_indx_merge))
